import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import './index.scss'


type FuSwipeCells = {
  renderRight: any,
  rightWidth: number,
  defalutOpen?: boolean,
  onChang?: (state: boolean) => void,
}


class FuSwipeCell extends Component<FuSwipeCells> {

  state = {
    open: this.props.defalutOpen || false,
    startX: 0, //开始坐标
    startY: 0
  }

  componentWillMount() { }

  componentWillReact() { }

  componentDidMount() { }

  componentWillUnmount() { }

  componentDidShow() { }

  componentDidHide() { }

  angle = (start, end) => {
    let _X = end.X - start.X,
      _Y = end.Y - start.Y
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  }

  close = () => {
    this.setState({ open: false })
  }

  render() {
    const { open } = this.state;
    const { rightWidth } = this.props;
    return (
      <View className={
        "fu-swiper-cell " +
        (open ? "fu-touch-move-active" : "")
      }
        onTouchStart={(e) => {
          let startMoveX = e.changedTouches[0].clientX;
          let startMoveY = e.changedTouches[0].clientY;
          this.setState({ startX: startMoveX, startY: startMoveY })
        }}
        onTouchMove={(e) => {
          const { open, startX = 0, startY = 0 } = this.state;
          let touchX = e.changedTouches[0].clientX;
          let touchY = e.changedTouches[0].clientY;
          let angle = this.angle({ X: startX, Y: startY }, { X: touchX, Y: touchY });
          if (Math.abs(angle) > 30) return;
          this.setState({ open: touchX < startX })
        }}
        onTouchCancel={this.close}
        onTouchForceChange={this.close}
      >
        <View className="fu-swiper-cell-content">
          {this.props.children}
        </View>
        <View onClick={this.close} className="fu-swiper-cell-option"
          style={open ? {} : {
            transform: `translateX(${rightWidth}px)`,
            marginLeft: `-${rightWidth}px`,
          }}
        >
          {this.props.renderRight}
        </View>
      </View >
    )
  }
}

export default FuSwipeCell
